﻿@model Kooboo.CMS.Content.Services.CategoryContents
@using Kooboo.Web.Script.Serialization
@using Kooboo.CMS.Content.Models
@{
    var categoryFolder = (Model.CategoryFolder).AsActual();
    var categories = Model.Contents.Select(it => new { Text = it.GetSummary(), UUID = it.UUID });
    var categoriesJson = categories.ToJSON();
    var categoryTemplateId = Kooboo.UniqueIdGenerator.GetInstance().GetBase32UniqueId(10);
}
<tr>
    <th>
        <label>
            @(string.IsNullOrEmpty(categoryFolder.DisplayName) ? categoryFolder.Name : categoryFolder.DisplayName)
        </label>
    </th>
    <td>
        <div id="@categoryTemplateId" class="category-list clearfix">
            <ul data-bind="foreach: data">
                <li class="category-item-data">
                    <span class="text left" data-bind="{text:Text}"></span>
                    <a class="remove right" data-bind="click: $parent.removeItem">@Html.IconImage("minus small")</a>
                </li>
            </ul>
            <input type="hidden" name="@("cat_" + Model.CategoryFolder.FullName + "_value")" data-bind="{value:postValue}" />
            <input type="hidden" name="@("cat_" + Model.CategoryFolder.FullName + "_value_old")" value="@string.Join(",", categories.Select(it => it.UUID).ToArray())" />
            <a href="@Html.Raw(Url.Action("SelectCategories", new { siteName = ViewContext.RequestContext.GetRequestValue("siteName"), repositoryName = ViewContext.RequestContext.GetRequestValue("RepositoryName"), folderName = Model.CategoryFolder.FullName, singleChoice = Model.SingleChoice }))" class="action categoryButton">@Html.IconImage("plus small")</a>

            <script>
                $(function () {
                    function CategoryViewModel() {
                        var self = this;
                        self.data = ko.observableArray(@Html.Raw(categoriesJson));
                        self.removeItem = function () {
                            window.leaveConfirm.stop();
                            self.data.remove(this);
                        };
                        self.removeByUUID=function(uuid){
                            var item = self.findByUUID(uuid);
                            console.log(item);
                            if (item!=null) {
                                self.data.remove(item);
                            }
                        };
                        self.findByUUID= function(uuid)
                        {
                            return  _.find(self.data(),function(item){
                                return item.UUID== uuid;
                            });
                        };
                        self.addItem = function (uuid, text) {
                            var item = self.findByUUID(uuid);
                            if (item==null) {
                                window.leaveConfirm.stop();
                                self.data.push({ UUID: uuid, Text: text });
                            }
                        };
                        self.postValue = ko.computed(function () {
                            var uuid = [];
                            _.each(this.data(), function (item) {
                                uuid.push(item.UUID);
                            });
                            return uuid.join(',');
                        }, this);
                    }
                    var categoryViewModel = new CategoryViewModel();
                    var categoryTemplate = $('#@categoryTemplateId');
                    ko.applyBindings(categoryViewModel, categoryTemplate[0]);

                    categoryTemplate.find('a.categoryButton').click(function (e) {
                        e.preventDefault();
                        var $categoryLink = $(this);

                        $categoryLink.pop({
                            popupOnTop: true,
                            width: 700,
                            height: 500,
                            dialogClass: 'iframe-dialog',
                            onclose: function () {
                                setTimeout(function () {
                                    if ($.popContext.getCurrent() != null) {
                                        $.popContext.getCurrent().find('iframe').height('100%');
                                    }
                                }, 16);
                            },
                            onload: function (currentHandle, pop, config) {
                                var iframe = pop.children('iframe'),
                                iframeSrc = iframe[0].contentWindow.document.location.href;
                                if (iframeSrc == 'about:blank') {
                                    return false;
                                }
                                var contents = iframe.contents();
                                var trClickHandler= function($tr)
                                {
                                    var text = $tr.find('td:eq(1)').text(),
                                        uuid = $tr.attr('id');
                                    if ($tr.hasClass('active')) {
                                        categoryViewModel.addItem(uuid, text);
                                    }
                                    else {
                                        categoryViewModel.removeByUUID(uuid);
                                    }
                                };
                                var $rootTrs = contents.find('tr');
                                var bindTrHandlers=function($trs)
                                {
                                    _.each(categoryViewModel.data(), function (item, index) {
                                        var $tr = contents.find('tr#' + item.UUID);
                                        $tr.addClass('active');
                                        $tr.find('input.select').attr('checked', 'checked');
                                    });
                                    $trs.click(function(){
                                        var $tr = $(this);
                                        trClickHandler($tr);
                                    });
                                    $trs.bind('treeNodeLoaded', function (e, treeNode) {                                        
                                        bindTrHandlers($(treeNode));
                                    });
                                };
                                bindTrHandlers($rootTrs);
                                (function initButton() {
                                    var saveBtn = contents.find('.save'),
                                    cancelBtn = contents.find('.cancel');
                                    cancelBtn.click(function () {
                                        pop.close();
                                    });
                                    saveBtn.click(function () {
                                        pop.close();
                                    });

                                })();
                            }
                        });
                    }).click();

                });
            </script>
        </div>
    </td>
</tr>
